/**
 * Copyright 2014 lerry
 * 
 * All right reserved.
 * 
 * Dec 23, 2014
 */
package com.bac.bacplatform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response.Listener;
import com.bac.javabeans.Location;
import com.bac.utils.Config;
import com.bac.utils.Util;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @author lerry
 */
public class FuelingGasActivity extends BaseActivity {

	/**
	 * MapView 是地图主控件
	 */

	RoutePlanSearch mSearch = null;

	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private Marker mMarkerA, mMarkerB;
	private InfoWindow mInfoWindow;

	private LatLng stLatLng;

	private List<Location> ll;

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();

	boolean isFirstLoc = true;// 是否首次定位

	// 初始化全局 bitmap 信息，不用时及时 recycle
	BitmapDescriptor bd_yes = BitmapDescriptorFactory
			.fromResource(R.drawable.fueling_icon_coupon);
	BitmapDescriptor bd_no = BitmapDescriptorFactory
			.fromResource(R.drawable.fueling_icon_fillingstation);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fueling_gas);

		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		// 地图缩放比例
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
		mBaiduMap.setMapStatus(msu);

		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		option.setIsNeedAddress(true);
		mLocClient.setLocOption(option);
		mLocClient.start();
		
		findViewById(R.id.title_left).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finishActivityOut();
			}
		});
	}

	@Override
	public void init() {
	}

	public void initOverLay(List<Location> location, LatLng mylat) {
		for (int i = 0; i < location.size(); i++) {
			LatLng gasStation = new LatLng(location.get(i).getLatitude(),
					location.get(i).getLongitude());
			if (location.get(i).getDetail().isPromoting()) {
				OverlayOptions oo = new MarkerOptions().position(gasStation)
						.icon(bd_yes).zIndex(9);
				mMarkerA = (Marker) (mBaiduMap.addOverlay(oo));
				mMarkerA.setTitle("yes");
			} else {
				OverlayOptions oo = new MarkerOptions().position(gasStation)
						.icon(bd_no).zIndex(7);
				mMarkerB = (Marker) (mBaiduMap.addOverlay(oo));
				mMarkerB.setTitle("no");
			}
		}

		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(mylat);
		mBaiduMap.setMapStatus(u);
		mBaiduMap.setOnMapClickListener(new OnMapClickListener() {

			@Override
			public boolean onMapPoiClick(MapPoi arg0) {
				return false;
			}

			@Override
			public void onMapClick(LatLng arg0) {
				mBaiduMap.hideInfoWindow();
			}
		});

		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(final Marker marker) {
				Location lt = null;
				for (int i = 0; i < ll.size(); i++) {
					if (ll.get(i).getLatitude() == marker.getPosition().latitude
							&& ll.get(i).getLongitude() == marker.getPosition().longitude) {
						lt = ll.get(i);
					}
				}

				LayoutInflater inflater = LayoutInflater
						.from(getApplicationContext());
				View view = inflater.inflate(R.layout.gas_popup, null);
				LinearLayout imgGift = (LinearLayout) view
						.findViewById(R.id.lay_gift);
				TextView discounTextView = (TextView) view
						.findViewById(R.id.tv_has_gift);
				TextView stationTextView = (TextView) view
						.findViewById(R.id.tv_address);
				stationTextView.setText(lt.getName());

				final Location lt2 = lt;
				stationTextView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intentToStation = new Intent(
								getApplicationContext(),
								GasInformationActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("location", lt2);
						intentToStation.putExtras(bundle);
						intentToStation.putExtra("end_jd",
								marker.getPosition().latitude + "");
						intentToStation.putExtra("end_wd",
								marker.getPosition().longitude + "");
						intentToStation.putExtra("st_jd", stLatLng.latitude
								+ "");
						intentToStation.putExtra("st_wd", stLatLng.longitude
								+ "");
						startActivity(intentToStation);
					}
				});
				view.setBackgroundResource(R.drawable.fueling_bg_bubble);
				view.findViewById(R.id.text_go).setOnClickListener(
						new OnClickListener() {
							@Override
							public void onClick(View v) {
								Toast.makeText(getApplicationContext(),
										"go map ", Toast.LENGTH_SHORT).show();
								mBaiduMap.hideInfoWindow();
								Intent intent = new Intent();
								intent.setClass(FuelingGasActivity.this,
										GoToGasActivity.class);
								intent.putExtra("end_jd",
										marker.getPosition().latitude + "");
								intent.putExtra("end_wd",
										marker.getPosition().longitude + "");
								intent.putExtra("st_jd", stLatLng.latitude + "");
								intent.putExtra("st_wd", stLatLng.longitude
										+ "");
								startActivityIn(intent);
							}
						});
				if ("yes".equals(marker.getTitle())) {
					LatLng ll = marker.getPosition();
					mInfoWindow = new InfoWindow(view, ll, -65);
					mBaiduMap.showInfoWindow(mInfoWindow);
				} else {
					LatLng ll = marker.getPosition();
					imgGift.setBackgroundResource(R.drawable.fueling_bg_discount_no);
					discounTextView.setText("无优惠");
					mInfoWindow = new InfoWindow(view, ll, -65);
					mBaiduMap.showInfoWindow(mInfoWindow);
				}

				return true;
			}
		});
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
//				mBaiduMap.animateMapStatus(u);
				mBaiduMap.setMapStatus(u);
				getGasStation(location);
			}

			stLatLng = new LatLng(location.getLatitude(),
					location.getLongitude());
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	/**
	 * 通过当前坐标查找附近加油站
	 * 
	 * @param location
	 *            当前位置
	 */
	public void getGasStation(final BDLocation location) {
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.i("TAG----success", response.toString());
				Gson gson = new Gson();
				ll = new ArrayList<Location>();
				ll = gson.fromJson(response, new TypeToken<List<Location>>() {
				}.getType());
				initOverLay(
						ll,
						new LatLng(location.getLatitude(), location
								.getLongitude()));
			}
		};

		String path = Config.URL_GAS_STATION;
		Map<String, String> map = new HashMap<String, String>();
		map.put("longitude", "" + location.getLongitude());
		map.put("latitude", "" + location.getLatitude());
		map.put("range", "5000");
		map.put("city", location.getCity());
		Util.httpStringPost(path, sListener, this, map);
	}

	@Override
	protected void onPause() {
		// MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		// MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 销毁定位，关闭地图
		Log.i("FuelingGasActivity-----", "onDestroy");
		mLocClient.stop();
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
		// 回收 bitmap 资源
		bd_yes.recycle();
		bd_no.recycle();
	}
}
